<script setup lang="ts">
import { ref, reactive, nextTick } from "vue";
import { centerMap, GETNOBASE, getRechargeData } from "@/api";
import { registerMap, getMap } from "echarts/core";
import { optionHandle, regionCodes } from "./center.map";
import BorderBox13 from "@/components/datav/border-box-13";
import { ElMessage } from "element-plus";

import type { MapdataType,ProvinceData } from "./center.map";

const maxAmount = ref(0);
const option = ref({});
const code = ref("china"); //china 代表中国 其他地市是行政编码
const state = reactive({
  totalList:[]
})

const provinceTotal = ref<ProvinceData[]>([]);



const getRecharge = async () => {
  const res = await getRechargeData();
  maxAmount.value = res.data.maxAmount;
  state.totalList = res.data.cityData;
  
  let provinceCount = {};
  state.totalList.forEach((item: any) => {
    const { province, count } = item;
    // 过滤无效省份（比如“荆州区草市”这种非省份数据）
    if (!province || province.includes('市') && !['北京市', '上海市', '天津市', '重庆市'].includes(province)) {
      return;
    }
    provinceCount[province] = (provinceCount[province] || 0) + count;
  });

  provinceTotal.value = Object.entries(provinceCount).map(([province, total]) => ({
    name: province,
    value: total
  }));

  console.log(provinceTotal.value);
  // 2. 数据生成后，再调用 getData，传入“china”渲染全国地图
  getData('china'); 
};

getRecharge()


const dataSetHandle = async (regionCode: string, list: object[]) => {
  const geojson: any = await getGeojson(regionCode);
  let cityCenter: any = {};
  let mapData: MapdataType[] = [];
  //获取当前地图每块行政区中心点
  geojson.features.forEach((element: any) => {
    cityCenter[element.properties.name] = element.properties.centroid || element.properties.center;
  });
  //当前中心点如果有此条数据中心点则赋值x，y当然这个x,y也可以后端返回进行大点，前端省去多行代码
  list.forEach((item: any) => {
    if (cityCenter[item.city]) { 
      mapData.push({
        name: item.city,
        value: cityCenter[item.city].concat(item.count),
      });
    }
  });
  await nextTick();

  option.value = optionHandle(regionCode, list, mapData);
};

// const getData = async (regionCode: string) => {
//   centerMap({ regionCode: regionCode })
//     .then((res) => {
//       console.log("中上--设备分布", res);
//       if (res.success) {
//         dataSetHandle(res.data.regionCode, res.data.dataList);
//       } else {
//         ElMessage.error(res.msg);
//       }
//     })
//     .catch((err) => {
//       ElMessage.error(err);
//     });
// };

const getData = async (regionCode: string) => {
  if (regionCode === 'china') {
    await dataSetHandle(regionCode, provinceTotal.value);
  } else {
    const provinceName = Object.keys(regionCodes).find(name => regionCodes[name].adcode === regionCode);
    if (!provinceName) {
      ElMessage.error('未找到该省份数据');
      return;
    }

    // 关键修改：转换为 { name: 地市名, value: count } 的格式
    const cityList = state.totalList
      .filter(item => item.province === provinceName)
      .map(item => ({
        name: item.city, // 地市名
        value: item.count // 数量值，用于视觉映射
      }));
    console.log('地市数据格式：', cityList);
    await dataSetHandle(regionCode, cityList);
  }
};
const getGeojson = (regionCode: string) => {
  return new Promise<any>(async (resolve) => {
    let mapjson = getMap(regionCode);
    if (mapjson) {
      mapjson = mapjson.geoJSON;
      resolve(mapjson);
    } else {
      mapjson = await GETNOBASE(`./map-geojson/${regionCode}.json`).then((data) => data);
      code.value = regionCode;
      registerMap(regionCode, {
        geoJSON: mapjson as any,
        specialAreas: {},
      });
      resolve(mapjson);
    }
  });
};


const mapClick = (params: any) => {

  console.log('这是点击事件',params);
  let xzqData = regionCodes[params.name];
  if (xzqData) {
    getData(xzqData.adcode);
  } else {
    window["$message"].warning("暂无下级地市");
  }
};
</script>

<template>
  <div class="centermap">
    <div class="maptitle">
      <div class="zuo"></div>
      <span class="titletext">当月营收总额(元):{{ maxAmount }}</span>
      <div class="you"></div>
    </div>
    <div class="mapwrap">
      <BorderBox13>
        <div class="quanguo" @click="getData('china')" v-if="code !== 'china'">中国</div>
        <v-chart
          class="chart"
          :option="option"
          ref="centerMapRef"
          @click="mapClick"
          v-if="JSON.stringify(option) != '{}'"
        />
      </BorderBox13>
    </div>
  </div>
</template>

<style scoped lang="scss">
.centermap {
  margin-bottom: 30px;

  .maptitle {
    height: 60px;
    display: flex;
    justify-content: center;
    padding-top: 10px;
    box-sizing: border-box;

    .titletext {
      font-size: 28px;
      font-weight: 900;
      letter-spacing: 6px;
      background: linear-gradient(92deg, #0072ff 0%, #00eaff 48.8525390625%, #01aaff 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      margin: 0 10px;
    }

    .zuo,
    .you {
      background-size: 100% 100%;
      width: 29px;
      height: 20px;
      margin-top: 8px;
    }

    .zuo {
      background: url("@/assets/img/xiezuo.png") no-repeat;
    }

    .you {
      background: url("@/assets/img/xieyou.png") no-repeat;
    }
  }

  .mapwrap {
    height: 580px;
    width: 100%;
    // padding: 0 0 10px 0;
    box-sizing: border-box;
    position: relative;

    .quanguo {
      position: absolute;
      right: 20px;
      top: -46px;
      width: 80px;
      height: 28px;
      border: 1px solid #00eded;
      border-radius: 10px;
      color: #00f7f6;
      text-align: center;
      line-height: 26px;
      letter-spacing: 6px;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 237, 237, 0.5), 0 0 6px rgba(0, 237, 237, 0.4);
      z-index: 10;
    }
  }
}
</style>